package com.bgn.baseframe.view.picture;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.bgn.baseframe.R;
import com.bgn.baseframe.base.BaseActivity;
import com.bgn.baseframe.utils.BaseFileUtil;
import com.bgn.baseframe.utils.ToastUtil;
import com.bgn.baseframe.utils.UiUtil;
import com.huantansheng.easyphotos.EasyPhotos;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.ArrayList;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by WL on 2018年6月26日 16:43:43.
 */


public class SelectPictureActivity extends BaseActivity implements View.OnClickListener {
    TextView tvPhotograph;
    TextView tvPhotographCrop;
    TextView tvAlbum;
    TextView tvAlbumCrop;
    TextView tvAlbumMult;
    TextView tvCancel;
    /*多选最大值*/
    private final int maxCount = 9;
    private final int maxFileSize = 100;//KB
    private final int REQUEST_CODE_CROP = 99;
    private final int REQUEST_CODE_PHOTO = 101;
    private final int REQUEST_CODE_PHOTO_CROP = 102;
    private final int REQUEST_CODE_ALBUM = 103;
    private final int REQUEST_CODE_ALBUM_CROP = 104;
    private final int REQUEST_CODE_ALBUM_MULT = 105;
    /*压缩后的新图片路径*/
    private ArrayList<String> newPaths = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_picture_dialog);
        initView();
    }

    private void initView() {
        tvPhotograph = findViewById(R.id.tv_photograph);
        tvPhotographCrop = findViewById(R.id.tv_photograph_crop);
        tvAlbum = findViewById(R.id.tv_album);
        tvAlbumCrop = findViewById(R.id.tv_album_crop);
        tvAlbumMult = findViewById(R.id.tv_album_mult);
        tvCancel = findViewById(R.id.tv_cancel);

        tvPhotograph.setOnClickListener(this);
        tvPhotographCrop.setOnClickListener(this);
        tvAlbum.setOnClickListener(this);
        tvAlbumCrop.setOnClickListener(this);
        tvAlbumMult.setOnClickListener(this);
        tvCancel.setOnClickListener(this);

    }


    public void takePhotograph() {

    }

    public void selectOneFromGallery() {

    }

    public void selectMaxCountFromGallery() {

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_photograph) {
            EasyPhotos.createCamera(this).setFileProviderAuthority(BaseFileUtil.FileProviderAuthorities).start(REQUEST_CODE_PHOTO);
        } else if (i == R.id.tv_photograph_crop) {
            EasyPhotos.createCamera(this).setFileProviderAuthority(BaseFileUtil.FileProviderAuthorities).start(REQUEST_CODE_PHOTO_CROP);
        } else if (i == R.id.tv_album) {
            EasyPhotos.createAlbum(this, false, GlideEngine.getInstance()).setFileProviderAuthority(BaseFileUtil.FileProviderAuthorities).setCount(1).start(REQUEST_CODE_ALBUM);
        } else if (i == R.id.tv_album_crop) {
            EasyPhotos.createAlbum(this, false, GlideEngine.getInstance()).setFileProviderAuthority(BaseFileUtil.FileProviderAuthorities).setCount(1).start(REQUEST_CODE_ALBUM_CROP);
        } else if (i == R.id.tv_album_mult) {
            EasyPhotos.createAlbum(this, false, GlideEngine.getInstance()).setFileProviderAuthority(BaseFileUtil.FileProviderAuthorities).setCount(9).start(REQUEST_CODE_ALBUM_MULT);
        } else {
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //不裁剪的情况
                case REQUEST_CODE_PHOTO:
                case REQUEST_CODE_ALBUM:
                case REQUEST_CODE_ALBUM_MULT:
                    //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
                    //ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                    //返回图片地址集合时如果你需要知道用户选择图片时是否选择了原图选项，用如下方法获取
                    //boolean selectedOriginal = data.getBooleanExtra(EasyPhotos.RESULT_SELECTED_ORIGINAL, false);
                    //返回图片地址集合：如果你只需要获取图片的地址，可以用这个
                    ArrayList<String> resultPaths = data.getStringArrayListExtra(EasyPhotos.RESULT_PATHS);
                    handleFileSize(resultPaths);
                    break;
                //裁剪的情况
                case REQUEST_CODE_PHOTO_CROP:
                case REQUEST_CODE_ALBUM_CROP:
                    //返回图片地址集合：如果你只需要获取图片的地址，可以用这个
                    ArrayList<String> resultPath2 = data.getStringArrayListExtra(EasyPhotos.RESULT_PATHS);
                    String oldPath = resultPath2.get(0);
                    newPaths.add(oldPath);
                    startPhotoZoom(oldPath);
                    break;
                //裁剪结束
                case REQUEST_CODE_CROP:
                    returnBackResult();
                    break;
            }
        }
    }

    public void startPhotoZoom(String path) {

        Uri inputUri;
        Uri outPutUri;//单独保存裁剪后的文件，不去覆盖原图
        String outputPath=BaseFileUtil.getImageDir()+File.separator+System.currentTimeMillis()+".jpg";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            inputUri = FileProvider.getUriForFile(this, BaseFileUtil.FileProviderAuthorities, BaseFileUtil.makeFileIfNotExists(path));
            outPutUri = FileProvider.getUriForFile(this, BaseFileUtil.FileProviderAuthorities, BaseFileUtil.makeFileIfNotExists(outputPath));
        } else {
            inputUri = Uri.fromFile(BaseFileUtil.makeFileIfNotExists(path));
            outPutUri = Uri.fromFile(BaseFileUtil.makeFileIfNotExists(outputPath));
        }


        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(inputUri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        //该参数可以不设定用来规定裁剪区的宽高比
        intent.putExtra("aspectX", 2);
        intent.putExtra("aspectY", 1);
        //该参数设定为你的imageView的大小
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 300);
        intent.putExtra("scale", true);
        //是否返回bitmap对象
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());//输出图片的格式
        intent.putExtra("noFaceDetection", true); // 头像识别
        startActivityForResult(intent, REQUEST_CODE_CROP);
    }


    /*处理压缩*/
    private void handleFileSize(ArrayList<String> resultPaths) {
        if (resultPaths == null) return;
        if (resultPaths.size() == 1) {
            Luban.with(UiUtil.getContext()).load(resultPaths.get(0)).ignoreBy(maxFileSize).setTargetDir(BaseFileUtil.getImageDir()).filter(new CompressionPredicate() {
                @Override
                public boolean apply(String path) {
                    return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                }
            }).setCompressListener(new OnCompressListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onSuccess(File file) {
                    newPaths.add(file.getPath());
                    returnBackResult();
                }

                @Override
                public void onError(Throwable e) {
                    ToastUtil.showInfo("压缩失败");
                    finish();
                }
            }).launch();
        } else {
            compressImageByPosition(0, resultPaths);
        }

    }


    private void compressImageByPosition(final int position, final ArrayList<String> resultPaths) {
        Luban.with(UiUtil.getContext()).load(resultPaths.get(position)).ignoreBy(80).setTargetDir(BaseFileUtil.getImageDir()).filter(new CompressionPredicate() {
            @Override
            public boolean apply(String path) {
                return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
            }
        }).setCompressListener(new OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(File file) {
                Logger.d("TTT:" + file.getPath());
                newPaths.add(file.getPath());
                if (position + 1 < resultPaths.size()) {
                    compressImageByPosition(position + 1, resultPaths);
                } else {
                    returnBackResult();
                }
            }

            @Override
            public void onError(Throwable e) {
                finish();
            }
        }).launch();
    }


    private void returnBackResult() {
        Intent resultIntent = new Intent();
        resultIntent.putExtra("path", newPaths.get(0));
        resultIntent.putExtra("paths", newPaths);
        setResult(RESULT_OK, resultIntent);
        finish();
    }

    //    private Uri getImageUri() {
//        /*设置头像路径*/
//        File file = BaseFileUtil.makeFileIfNotExists(BaseFileUtil.getImageDir() + "/" + BaseFileUtil.HEAD_IMAGE_FILENAME);
//
//        Uri imageUri = Uri.fromFile(file);
//        return imageUri;
//    }
//
//    private Uri getCamereImageUri() {
//        /*设置头像路径*/
//        File file = BaseFileUtil.makeFileIfNotExists(BaseFileUtil.getImageDir() + "/" + System.currentTimeMillis() + ".jpg");
//        Uri imageUri = Uri.fromFile(file);
//        return imageUri;
//    }
}
